package com.xuecheng.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.ucenter.feignclient.CheckCodeClient;
import com.xuecheng.ucenter.mapper.XcUserMapper;
import com.xuecheng.ucenter.model.dto.AuthParamsDto;
import com.xuecheng.ucenter.model.dto.XcUserExt;
import com.xuecheng.ucenter.model.po.XcUser;
import com.xuecheng.ucenter.service.AuthService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author zhupanlin
 * @version 1.0
 * @description: TODO
 * @date 2024/3/25 14:39
 */
@Service("password_authservice")
public class PasswordAuthServiceImpl implements AuthService {
    
    @Resource
    XcUserMapper xcUserMapper;
    
    @Resource
    PasswordEncoder passwordEncoder;
    
    @Resource
    CheckCodeClient checkCodeClient;
    
    
    @Override
    public XcUserExt execute(AuthParamsDto authParamsDto) {
        
        // 校验验证码

        // 输入的验证码
        /*String checkcode = authParamsDto.getCheckcode();
        // 验证码对应的key
        String key = authParamsDto.getCheckcodekey();

        if (StringUtils.isEmpty(checkcode) || StringUtils.isEmpty(key)) {
            throw new RuntimeException("请输入验证码");
        }

        // 远程调用验证码服务接口去校验验证码
        Boolean verify = checkCodeClient.verify(key, checkcode);
        if (verify == null || !verify){
            throw new RuntimeException("验证码输入错误");
        }*/

        //账号
        String username = authParamsDto.getUsername();
        XcUser user = xcUserMapper.selectOne(new LambdaQueryWrapper<XcUser>().eq(XcUser::getUsername, username));
        //取出数据库存储的正确密码
        String passwordDb  =user.getPassword();
        // 拿到用户输入的密码
        String passwordForm = authParamsDto.getPassword();
        // 校验密码
        boolean matches = passwordEncoder.matches(passwordForm, passwordDb);
        if (!matches){
            throw new RuntimeException("账号后密码错误");
        }
        XcUserExt xcUserExt = new XcUserExt();
        BeanUtils.copyProperties(user, xcUserExt);

        return xcUserExt;
    }
}
